package com.xlh.job;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.xlh.dto.user.UserInfoDTO;
import com.xlh.enums.user.UserStatusEnum;
import com.xlh.param.user.UpdateUserStatusParam;
import com.xlh.service.user.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账号销户任务
 * <p>
 * Created by lx on 2019/4/29.
 */
@Component
public class AccountCancellationTask {

    private final static Logger LOGGER = LoggerFactory.getLogger(AccountCancellationTask.class);

    @Autowired
    private UserService userService;

    @Scheduled(cron = "0 0 0 * * *")
    public void accountCancellation() {

        try {

            List<UserInfoDTO> userInfoDTOS = userService.listUser(null, null,
                    Lists.newArrayList(UserStatusEnum.NOT_DELETE.getCode()), null);
            if (CollectionUtils.isEmpty(userInfoDTOS)) return;

            userInfoDTOS = userInfoDTOS.stream().filter(userInfoDTO -> userInfoDTO.getDestroyTime() != null
                    && userInfoDTO.getDestroyTime().getTime() <= DateUtil.offsetDay(new Date(), -1).getTime())
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userInfoDTOS)) return;

            // 销户
            UpdateUserStatusParam param = new UpdateUserStatusParam();
            param.setStatus(UserStatusEnum.ACCOUNT_CANCELLATION.getCode());
            userService.updateUserStatus(
                    userInfoDTOS.stream().map(UserInfoDTO::getId).collect(Collectors.toList()), param);

        } catch (Exception e) {
            LOGGER.error("销户失败", e);
        }

    }
}
